//
//  NSString+BMLDES.m
//  24-加密
//
//  Created by GivenBmli on 16/8/16.
//  Copyright © 2016年 GivenBmli. All rights reserved.
//

#import "NSString+BMLDES.h"
#import "NSString+BMLBase64.h"
#import <CommonCrypto/CommonCrypto.h>
// 必须八位
#define key @"01234567"
// 向量
static Byte iv[] = {1,2,3,4,5,6,7,8};
@implementation NSString (BMLDES)
// 字符串对称加密(DES)
- (NSString *)stringWithDES {
//    1.将字符串本身转换成C字符串
    const char *sting = [self UTF8String];
//    2. 接收容器
    unsigned char byte [1024];
//    3.容器大小
    size_t dataOutMoed = 0;
//    4.DES加密过程
/**
 参数1: 加密/解密
 参数2: 加密/解密 方式
 参数3: 分组密码的选择
 参数4: 密钥
 参数5: 密钥大小
 参数6: 向量
 参数7: C的字符串
 参数8: 字符串长度length
 参数9: 接收容器
 参数10: 容器大小
 参数11: 容器最终的个数
   */
   CCCryptorStatus cryptorStatus = CCCrypt(kCCEncrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, [key UTF8String], kCCKeySizeDES, iv, sting, strlen(sting), byte, 1024, &dataOutMoed);
//    5.判断是否成功
    if (cryptorStatus == kCCSuccess) {
//        转成字符串---- base64返回
        NSData *desData = [NSData dataWithBytes:byte length:dataOutMoed];
        
        NSString *dataBase64Sting = [desData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        return dataBase64Sting;
//        NSLog(@"成功");
    }else {
        NSLog(@"加密失败");
    return nil;
    }
}
// 字符串对称解密(DES)
- (NSString *)desWithSting {
    NSData *data = [self base64StringWithData];
    const void *byte = data.bytes;
    unsigned char buffer [1024];
    size_t dataOutMoed = 0;
    CCCryptorStatus cryptorStatus = CCCrypt(kCCDecrypt, kCCAlgorithmDES, kCCOptionPKCS7Padding, [key UTF8String], kCCKeySizeDES, iv, byte,  [data length],buffer, 1024, &dataOutMoed);
    if (cryptorStatus == kCCSuccess) {
        NSData *sourceData = [[NSData alloc] initWithBytes:buffer length:dataOutMoed];
        NSString *sourceString = [[NSString alloc] initWithData:sourceData encoding:NSUTF8StringEncoding];
        return sourceString;
    }else {
        
        NSLog(@"失败");
    return nil;
    }
}
@end
